package com.example.list.sqlite;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.list.R;

import java.util.ArrayList;

public class SQLiteActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText etAdd;
    private Button btnAdd;

    private EditText etDelete;
    private Button btnDelete;

    private EditText etModifyBefore;
    private EditText etModifyAfter;
    private Button btnModify;

    private Button btnQuery;
    private TextView tvResult;

    SQLiteDatabase db;
    private RecyclerView rv_db;

    int operateType;
    long result;
    ArrayList listDB = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_s_q_lite);

        //依靠DatabaseHelper带全部参数的构造函数创建数据库
        DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this, Constants.DATABASE_NAME, null, Constants.VERSION_CODE);
        db = dbHelper.getWritableDatabase();
//————————————————
//        版权声明：本文为CSDN博主「midnight_time」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//        原文链接：https://blog.csdn.net/midnight_time/article/details/80834198


        etAdd = (EditText) findViewById(R.id.et_add);
        btnAdd = (Button) findViewById(R.id.btn_add);

        etDelete = (EditText) findViewById(R.id.et_delete);
        btnDelete = (Button) findViewById(R.id.btn_delete);

        etModifyBefore = (EditText) findViewById(R.id.et_modify_before);
        etModifyAfter = (EditText) findViewById(R.id.et_modify_after);
        btnModify = (Button) findViewById(R.id.btn_modify);

        btnQuery = (Button) findViewById(R.id.btn_query);
        tvResult = (TextView) findViewById(R.id.tv_result);
        rv_db = (RecyclerView) findViewById(R.id.rv_db);
        btnAdd.setOnClickListener(this);

        btnDelete.setOnClickListener(this);

        btnQuery.setOnClickListener(this);
        btnModify.setOnClickListener(this);


        query();
    }

    @Override
    public void onClick(View v) {
        String insert_data = etAdd.getText().toString().trim();
        String delete_data = etDelete.getText().toString().trim();
        String update_before_data = etModifyBefore.getText().toString().trim();
        String update_after_data = etModifyAfter.getText().toString().trim();

        switch (v.getId()) {

            case R.id.btn_add://增
                //创建存放数据的ContentValues对象
                if (listDB.contains(insert_data)) {
                    Toast.makeText(this, "已存在该数据，不可重复插入", Toast.LENGTH_SHORT).show();
                    return;
                }
                ContentValues values = new ContentValues();
                values.put("name", insert_data);
                switch (Constants.VERSION_CODE) {
                    case 2:
                        values.put("age", 20);
                        break;
                    case 3:
                        values.put("age", 20);
                        values.put("sex", "男");
                        break;
                }

                //数据库执行插入命令
                result = db.insert(Constants.TABLE_NAME, null, values);

                operateType = 1;
                showToastType(result, operateType);
                etAdd.setText("");
                break;


            case R.id.btn_query://查
                //创建游标对象
                query();

                break;

            case R.id.btn_delete://删
                result = db.delete(Constants.TABLE_NAME, "name=?", new String[]{delete_data});
                operateType = 2;
                showToastType(result, operateType);
                etDelete.setText("");
                break;

            case R.id.btn_modify://改
                ContentValues values2 = new ContentValues();
                values2.put("name", update_after_data);
                result = db.update(Constants.TABLE_NAME, values2, "name = ?", new String[]{update_before_data});
                operateType = 3;
                showToastType(result, operateType);
                etModifyBefore.setText("");
                etModifyAfter.setText("");
                break;


        }

    }

    private void showToastType(long result, int operateType) {
        switch (operateType) {
            case 1:
                if (result == -1) {
                    Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
                    query();
                }
                break;

            case 2:
                if (result == 1) {
                    Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                    query();
                } else {
                    Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
                }
                break;

            case 3:
                if (result == 1) {
                    Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                    query();
                } else {
                    Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
                }
                break;
        }

    }

    private void query() {
        Cursor cursor = db.query(Constants.TABLE_NAME, new String[]{"name","age"}, null, null, null, null, null);
        //利用游标遍历所有数据对象

        listDB.clear();
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String age = cursor.getString(cursor.getColumnIndex("age"));

            listDB.add(name+","+age);
        }



        final MyAdapterDB adapter = new MyAdapterDB(this, listDB);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rv_db.setLayoutManager(layoutManager);
        rv_db.setAdapter(adapter);
        // 关闭游标，释放资源
        cursor.close();
    }

    public  void queryRow(){//查询一行所有列数据
        String selectQuery="SELECT * FROM "+Constants.TABLE_NAME;
        Cursor cursor = db.rawQuery(selectQuery, null);
        cursor.moveToFirst();

        int colNum = cursor.getColumnCount();

        do{
            StringBuffer stringBuffer=new StringBuffer();
            for(int i=0;i<colNum;++i){
                if (i==colNum-1) {
                    stringBuffer.append(cursor.getString(i));
                }else {
                    stringBuffer.append(cursor.getString(i)+",");
                }
            }
            listDB.add(stringBuffer);
        }while (cursor.moveToNext());
    }
}